package library.server;

import java.sql.SQLException;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/Library")
public class LibraryServer {
	// private static final String USER = "root";
	// private static final String PASSWORD = "root";
	private DataSource ds;

	public LibraryServer() {
		Context initCtx;
		try {
			initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");
			ds = (DataSource) envCtx.lookup("jdbc/LibraryDB");
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@PUT
	@Consumes("application/xml")
	@Produces(MediaType.APPLICATION_XML)
	public Response addBook(Book b) {
		MySQLConnection connection;
		Boolean result = false;
		try {
			connection = new MySQLConnection(ds);
			result = QueryMaker.insertBook(connection, b);
			connection.closeConnection();
		} catch (SQLException e) {
			result = false;
		}

		if(result){
			return Response.status(204).build();
		}
		else{
			return Response.status(400).build();
		}
	}

	

	@DELETE
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_XML)
	public Response deleteBook(@QueryParam("isdn") String isdn) {
		MySQLConnection connection;
		Boolean result = false;
		try {
			connection = new MySQLConnection(ds);
			result = QueryMaker.deleteBook(connection, isdn);
			connection.closeConnection();
		} catch (SQLException e) {
			result = false;
		}

		if(result){
			return Response.status(204).build();
		}
		else{
			return Response.status(404).entity("Book with the id " + isdn + " is not present in the database").build();
		}
	}

	@GET
	@Produces("application/xml")
	public GenericEntity<List<Book>> getAllBooks() {
		MySQLConnection connection;
		List<Book> result;
		try {
			connection = new MySQLConnection(ds);
			result = QueryMaker.getAllBooks(connection);
			connection.closeConnection();
		} catch (SQLException e) {
			result = null;
		}
		
		return new GenericEntity<List<Book>>(result){};
	}

}
